<template>
  <div class="course-detail">
    <van-nav-bar
      title="课程详情"
      left-arrow
      @click-left="onClickLeft"
    />
    
    <!-- 课程封面 -->
    <van-image
      :src="course.image"
      class="course-cover"
      fit="cover"
    />

    <!-- 课程信息 -->
    <div class="course-info">
      <h1 class="title">{{ course.name }}</h1>
      <div class="meta">
        <span><van-icon name="friends-o" /> {{ course.students }}人学习</span>
        <span><van-icon name="clock-o" /> {{ course.duration }}</span>
      </div>
      <div class="price-box">
        <span class="price">¥{{ course.price }}</span>
        <span class="original-price">¥{{ course.originalPrice }}</span>
      </div>
    </div>

    <!-- 课程详情tabs -->
    <van-tabs v-model:active="activeTab" sticky>
      <!-- 课程介绍 -->
      <van-tab title="课程介绍">
        <div class="tab-content">
          <div class="section">
            <h3>课程简介</h3>
            <p>{{ course.description }}</p>
          </div>
          <div class="section">
            <h3>课程大纲</h3>
            <van-collapse v-model="activeChapters">
              <van-collapse-item 
                v-for="chapter in course.chapters" 
                :key="chapter.id"
                :title="chapter.title"
                :name="chapter.id"
              >
                <div 
                  v-for="lesson in chapter.lessons" 
                  :key="lesson.id"
                  class="lesson-item"
                >
                  <van-icon name="play-circle-o" />
                  <span class="lesson-title">{{ lesson.title }}</span>
                  <span class="lesson-duration">{{ lesson.duration }}</span>
                </div>
              </van-collapse-item>
            </van-collapse>
          </div>
        </div>
      </van-tab>
      
      <!-- 课程评价 -->
      <van-tab title="课程评价">
        <div class="tab-content">
          <div class="rating-overview">
            <div class="rating-score">
              <span class="score">{{ course.rating }}</span>
              <van-rate v-model="course.rating" readonly allow-half />
            </div>
            <div class="rating-tags">
              <van-tag 
                v-for="tag in course.ratingTags" 
                :key="tag.name"
                plain 
                type="primary"
              >
                {{ tag.name }} ({{ tag.count }})
              </van-tag>
            </div>
          </div>
          <div class="reviews">
            <van-list
              v-model:loading="loading"
              :finished="finished"
              finished-text="没有更多了"
              @load="onLoad"
            >
              <div 
                v-for="review in reviews" 
                :key="review.id"
                class="review-item"
              >
                <div class="user-info">
                  <van-image
                    :src="review.avatar"
                    round
                    width="40"
                    height="40"
                  />
                  <div class="user-meta">
                    <span class="username">{{ review.username }}</span>
                    <van-rate v-model="review.rating" readonly allow-half />
                  </div>
                  <span class="review-time">{{ review.time }}</span>
                </div>
                <p class="review-content">{{ review.content }}</p>
              </div>
            </van-list>
          </div>
        </div>
      </van-tab>
    </van-tabs>

    <!-- 底部操作栏 -->
    <div class="bottom-bar">
      <div class="left">
        <van-button icon="star-o" plain>收藏</van-button>
        <van-button icon="share-o" plain @click="showShare = true">分享</van-button>
        <van-button plain type="warning" @click="togglePurchaseStatus">
          {{ isPurchased ? '模拟退款' : '模拟购买' }}
        </van-button>
      </div>
      <div class="right">
        <van-button type="primary" block @click="startLearning">立即学习</van-button>
      </div>
    </div>

    <!-- 分享面板 -->
    <van-share-sheet
      v-model:show="showShare"
      title="分享给好友"
      :options="shareOptions"
      @select="onShareSelect"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast, showSuccessToast } from 'vant'
import QRCode from 'qrcode'

const router = useRouter()
const route = useRoute()

// 页面状态
const activeTab = ref(0)
const activeChapters = ref([])
const loading = ref(false)
const finished = ref(false)
const isPurchased = ref(false)
const showShare = ref(false)

// 分享选项
const shareOptions = [
  { name: '微信', icon: 'wechat', className: 'share-green' },
  { name: '朋友圈', icon: 'wechat-moments', className: 'share-green' },
  { name: '微博', icon: 'weibo', className: 'share-red' },
  { name: 'QQ', icon: 'qq', className: 'share-blue' },
  { name: '复制链接', icon: 'link', className: 'share-black' },
  { name: '二维码', icon: 'qrcode', className: 'share-black' }
]

// 获取分享链接
const getShareUrl = computed(() => {
  const baseUrl = window.location.origin
  return `${baseUrl}${route.fullPath}`
})

// 获取分享内容
const getShareContent = computed(() => {
  return {
    title: course.value.name,
    desc: course.value.description,
    link: getShareUrl.value,
    image: course.value.image
  }
})

// 模拟课程数据
const course = ref({
  id: 1,
  name: '高中数学提高班 - 函数与导数专题',
  description: '本课程针对高考重点难点，系统讲解函数与导数知识点。通过大量例题和实战演练，帮助学生掌握解题技巧和方法。课程内容由经验丰富的一线教师精心设计，适合高中数学提升和备考。',
  image: 'https://img01.yzcdn.cn/vant/cat.jpeg',
  price: '299.00',
  originalPrice: '399.00',
  duration: '120分钟',
  students: 2150,
  rating: 4.8,
  ratingTags: [
    { name: '讲解清晰', count: 521 },
    { name: '通俗易懂', count: 432 },
    { name: '干货满满', count: 321 },
    { name: '案例丰富', count: 265 }
  ],
  chapters: [
    {
      id: 1,
      title: '第一章：函数基础',
      lessons: [
        { id: 1, title: '1.1 函数的概念', duration: '15:00' },
        { id: 2, title: '1.2 函数的性质', duration: '20:00' },
        { id: 3, title: '1.3 函数图像', duration: '25:00' }
      ]
    },
    {
      id: 2,
      title: '第二章：导数入门',
      lessons: [
        { id: 4, title: '2.1 导数的定义', duration: '18:00' },
        { id: 5, title: '2.2 导数的几何意义', duration: '22:00' },
        { id: 6, title: '2.3 导数的运算法则', duration: '20:00' }
      ]
    }
  ]
})

// 模拟评论数据
const reviews = ref([
  {
    id: 1,
    username: '张同学',
    avatar: 'https://img01.yzcdn.cn/vant/cat.jpeg',
    rating: 5,
    content: '老师讲解非常清晰，举例也很贴近实际，很容易理解。课程内容充实，知识点讲解全面，非常适合高考复习。',
    time: '2023-08-01'
  },
  {
    id: 2,
    username: '李同学',
    avatar: 'https://img01.yzcdn.cn/vant/cat.jpeg',
    rating: 4.5,
    content: '课程质量很好，老师讲解通俗易懂，习题难度适中，很适合查漏补缺。',
    time: '2023-07-30'
  }
])

// 加载更多评论
const onLoad = () => {
  setTimeout(() => {
    reviews.value = [...reviews.value, ...reviews.value]
    loading.value = false
    finished.value = true
  }, 1000)
}

// 返回上一页
const onClickLeft = () => {
  router.back()
}

// 检查课程是否已购买
const checkPurchaseStatus = async (courseId) => {
  try {
    // 从localStorage获取购买状态
    const purchasedCourses = JSON.parse(localStorage.getItem('purchasedCourses') || '[]')
    isPurchased.value = purchasedCourses.includes(courseId)
    return isPurchased.value
  } catch (error) {
    console.error('检查购买状态失败:', error)
    return false
  }
}

// 切换购买状态（仅用于测试）
const togglePurchaseStatus = () => {
  try {
    const purchasedCourses = JSON.parse(localStorage.getItem('purchasedCourses') || '[]')
    const courseId = course.value.id
    
    if (isPurchased.value) {
      // 模拟退款
      const index = purchasedCourses.indexOf(courseId)
      if (index > -1) {
        purchasedCourses.splice(index, 1)
      }
      showToast('模拟退款成功')
    } else {
      // 模拟购买
      if (!purchasedCourses.includes(courseId)) {
        purchasedCourses.push(courseId)
      }
      showToast('模拟购买成功')
    }
    
    localStorage.setItem('purchasedCourses', JSON.stringify(purchasedCourses))
    isPurchased.value = !isPurchased.value
  } catch (error) {
    showToast('操作失败')
    console.error(error)
  }
}

// 开始学习
const startLearning = async () => {
  try {
    const isPurchased = await checkPurchaseStatus(course.value.id)
    
    if (isPurchased) {
      // 已购买，跳转到学习页面
      router.push({
        name: 'courseLearn',
        params: { 
          id: course.value.id 
        }
      })
    } else {
      // 未购买，跳转到订单创建页面
      router.push({
        path: `/order/create`,
        query: { 
          courseId: course.value.id 
        }
      })
    }
  } catch (error) {
    showToast('系统繁忙，请稍后再试')
  }
}

// 页面加载时检查购买状态
onMounted(async () => {
  await checkPurchaseStatus(course.value.id)
})

// 复制文本到剪贴板
const copyToClipboard = async (text) => {
  try {
    // 首先尝试使用 Clipboard API
    if (navigator.clipboard && window.isSecureContext) {
      await navigator.clipboard.writeText(text)
      return true
    }
    
    // 备用方案：创建临时输入框
    const textArea = document.createElement('textarea')
    textArea.value = text
    textArea.style.position = 'fixed'
    textArea.style.left = '-9999px'
    textArea.style.top = '-9999px'
    document.body.appendChild(textArea)
    textArea.focus()
    textArea.select()
    
    try {
      document.execCommand('copy')
      textArea.remove()
      return true
    } catch (err) {
      textArea.remove()
      return false
    }
  } catch (err) {
    return false
  }
}

// 处理分享选择
const onShareSelect = async (option) => {
  const shareContent = getShareContent.value
  
  switch (option.name) {
    case '微信':
      showToast('请在微信中打开分享')
      break
      
    case '朋友圈':
      showToast('请在微信中打开分享到朋友圈')
      break
      
    case '微博':
      const weiboUrl = `http://service.weibo.com/share/share.php?url=${encodeURIComponent(shareContent.link)}&title=${encodeURIComponent(shareContent.title)}&pic=${encodeURIComponent(shareContent.image)}`
      window.open(weiboUrl, '_blank')
      break
      
    case 'QQ':
      const qqUrl = `http://connect.qq.com/widget/shareqq/index.html?url=${encodeURIComponent(shareContent.link)}&title=${encodeURIComponent(shareContent.title)}&desc=${encodeURIComponent(shareContent.desc)}&pics=${encodeURIComponent(shareContent.image)}`
      window.open(qqUrl, '_blank')
      break
      
    case '复制链接':
      const success = await copyToClipboard(shareContent.link)
      if (success) {
        showSuccessToast('链接已复制')
      } else {
        showToast('复制失败，请手动复制链接：' + shareContent.link)
      }
      break
      
    case '二维码':
      try {
        const qrCodeDataUrl = await QRCode.toDataURL(shareContent.link)
        const link = document.createElement('a')
        link.href = qrCodeDataUrl
        link.download = `${course.value.name}-分享二维码.png`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        showSuccessToast('二维码已下载')
      } catch (err) {
        showToast('二维码生成失败')
      }
      break
  }
  
  showShare.value = false
}
</script>

<style lang="scss" scoped>
@use '../../styles/mixins.scss' as *;

.course-detail {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-bottom: 60px; // 增加底部padding，为底部操作栏留出空间

  .course-cover {
    width: 100%;
    height: 200px;
  }

  .course-info {
    background: #fff;
    padding: 16px;
    margin-bottom: 8px;

    .title {
      font-size: 18px;
      font-weight: 500;
      color: #323233;
      margin: 0 0 12px;
    }

    .meta {
      @include flex(row, flex-start);
      color: #969799;
      font-size: 14px;
      margin-bottom: 12px;

      span {
        margin-right: 16px;
        @include flex(row, flex-start);
        align-items: center;

        .van-icon {
          margin-right: 4px;
        }
      }
    }

    .price-box {
      @include flex(row, flex-start);
      align-items: center;

      .price {
        font-size: 20px;
        font-weight: 500;
        color: #ee0a24;
      }

      .original-price {
        font-size: 14px;
        color: #969799;
        text-decoration: line-through;
        margin-left: 8px;
      }
    }
  }

  .tab-content {
    padding: 16px;

    .section {
      margin-bottom: 20px;

      h3 {
        font-size: 16px;
        font-weight: 500;
        color: #323233;
        margin: 0 0 12px;
      }

      p {
        font-size: 14px;
        color: #666;
        line-height: 1.6;
        margin: 0;
      }
    }

    .lesson-item {
      @include flex(row, flex-start);
      align-items: center;
      padding: 12px 0;
      font-size: 14px;

      .van-icon {
        margin-right: 8px;
        color: #323233;
      }

      .lesson-title {
        flex: 1;
        color: #323233;
      }

      .lesson-duration {
        color: #969799;
      }
    }

    .rating-overview {
      background: #fff;
      padding: 16px;
      margin-bottom: 8px;

      .rating-score {
        @include flex(row, flex-start);
        align-items: center;
        margin-bottom: 12px;

        .score {
          font-size: 24px;
          font-weight: 500;
          color: #ee0a24;
          margin-right: 8px;
        }
      }

      .rating-tags {
        .van-tag {
          margin-right: 8px;
          margin-bottom: 8px;
        }
      }
    }

    .review-item {
      background: #fff;
      padding: 16px;
      margin-bottom: 8px;

      .user-info {
        @include flex(row, flex-start);
        align-items: center;
        margin-bottom: 12px;

        .user-meta {
          flex: 1;
          margin-left: 12px;

          .username {
            display: block;
            font-size: 14px;
            color: #323233;
            margin-bottom: 4px;
          }
        }

        .review-time {
          font-size: 12px;
          color: #969799;
        }
      }

      .review-content {
        font-size: 14px;
        color: #666;
        line-height: 1.6;
        margin: 0;
      }
    }
  }

  .bottom-bar {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 100; // 增加z-index确保在最上层
    background: #fff;
    padding: 8px 16px;
    @include flex(row, space-between);
    align-items: center;
    box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.06);

    .left {
      @include flex(row, flex-start);
      
      .van-button {
        margin-right: 8px;
      }
    }

    .right {
      flex: 1;
      margin-left: 16px;

      .van-button {
        width: 100%; // 确保按钮填满容器
      }
    }
  }

  // 分享按钮样式
  .share-green {
    color: #07c160;
  }

  .share-red {
    color: #ff5722;
  }

  .share-blue {
    color: #1989fa;
  }

  .share-black {
    color: #323233;
  }

  .van-share-sheet {
    &__option {
      .van-icon {
        font-size: 48px;
      }
    }
  }
}
</style>
